from flask import render_template, request, redirect, url_for, flash
from flask_login import login_user, logout_user
from app import db
from app.forms.auth import RegisterForm, LoginForm, ForgetPasswordForm, ResetPasswordForm
from app.libs.email import send_email
from app.models.user import User
from . import web


@web.route('/register', methods=['GET', 'POST'])
def register():
    form = RegisterForm(request.form)
    if request.method == 'POST' and form.validate():
        with db.auto_commit():
            user = User()
            user.set_attrs(form.data)
            db.session.add(user)
        return redirect(url_for('web.login'))

    return render_template('auth/register.html', form=form)


@web.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm(request.form)
    if request.method == 'POST' and form.validate():
        user = User.query.filter_by(email=form.email.data).first()

        if user and user.check_password(form.password.data):
            login_user(user, remember=True) # 往session中写入用户id信息,完成登陆操作
            next = request.args.get('next') # login模块会对请求url进行保存,我们可以根据这个url,让用户跳转到未登录时预览的页面.(提升体验)
            if not next or not next.startswith('/'): # 判断next是否以'/'开头,防止重定向攻击(重定向攻击是什么攻击?)
                next = url_for('web.index')
            return redirect(next)
        else:
            flash('用户名或密码错误')
    return render_template('auth/login.html', form=form)


@web.route('/reset/password', methods=['GET', 'POST'])
def forget_password_request():
    ''' 忘记密码最重要的就是确定用户的身份,所以在这里使用把用户信息加密的技术 '''
    form = ForgetPasswordForm(request.form)
    if request.method == 'POST':
        if form.validate():
            user = User.query.filter_by(email=form.email.data).first_or_404() # 404如果没找到,会抛出异常,并中断代码执行.
            send_email(form.email.data, '重置密码', 'email/reset_password.html', user=user, token=user.generate_token())
            flash('邮件已发送到' + form.email.data + '请注意查收')
    return render_template('auth/forget_password_request.html', form=form)


@web.route('/reset/password/<token>', methods=['GET', 'POST'])
def forget_password(token):
    form = ResetPasswordForm(request.form)
    if request.method == 'POST' and form.validate():
        sucess = User.reset_password(token, form.password1.data)
        if sucess:
            flash('重置密码成功')
            return redirect(url_for('web.login'))
        else:
            flash('重置密码失败')
    return render_template('auth/forget_password.html', form=form)


@web.route('/change/password', methods=['GET', 'POST'])
def change_password():
    pass


@web.route('/logout')
def logout():
    logout_user() # 基本逻辑是删除session里保存的值
    return redirect(url_for('web.index'))